package cn.desk.commons.util;

import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ListAddValueInjectionInvoker implements InjectionInvoker,
		ApplicationContextAware {
	protected static ApplicationContext context;
	private String propertyValue;
	private String reference;
	protected List<Object> target;

	@SuppressWarnings("unchecked")
	@Override
	public void invoke(Object target) {
		if(target instanceof List){
			this.target = (List<Object>) target;
			if (propertyValue == null && reference == null) {
				throw new RuntimeException();
			}
			if (propertyValue != null) {
				writeValue(propertyValue);
			} else {
				Object ref = context.getBean(reference);
				if(ref instanceof List){
					List<Object> list=(List<Object>) ref;
					for(Object o:list){
						writeValue(o);
					}
				}else{
					writeValue(ref);
				}
			}
		}else{
			throw new RuntimeException("bean:" +target+" is not a List");
		}
	}

	private void writeValue(Object value) {
		List<Object> list=(List<Object>) target;
		list.add(value);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		context = applicationContext;
	}

	public String getReference() {
		return reference;
	}

	public void setReference(String reference) {
		this.reference = reference;
	}

	public String getPropertyValue() {
		return propertyValue;
	}

	public void setPropertyValue(String propertyValue) {
		this.propertyValue = propertyValue;
	}

	@Override
	public void prepareInvoke() {
		
	}

	@Override
	public void afterInvoke() {
		
	}
}
